package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: UserController
 * @Author: Solomon
 * @Date: 2020/7/15 1:42
 * @Description:
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @RequestMapping("/getUsername")
    public Result getUsername(){
        Map map = new HashMap();
        //框架认证通过之后，会把当前用户存入上下文对象中，基于HttpSession
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user != null){
            map.put("username",user.getUsername());//当前登录用户名
            //当时查询用户时，封装的角色权限是list集合，
            Set<String> auths = AuthorityUtils.authorityListToSet(user.getAuthorities());
            map.put("auths",auths);
            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,map);
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

}
